package com.superhelper.superhelper_web.service.sms.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.superhelper.common.utils.CryptUtil;
import com.superhelper.superhelper_web.service.sms.SmsHandler;
import com.superhelper.superhelper_web.utils.HttpClientHelper;

/**
 * 漫道短信接口
 * 
 * @author duanshao
 * 
 */
public class MDSmsHandler implements SmsHandler {
	private final static Logger LOG = LoggerFactory.getLogger(SmsHandler.class);
	@Value("${sms.md.sn}")
	private String sn;
	@Value("${sms.md.pwd}")
	private String pwd;

	private String host;

	public void setHost(String host) {
		this.host = host;
	}

	private boolean isAlive = true;

	private int failTimes;

	private final String SEND_TEMPLATE = "%s/mdsmssend.ashx?sn=%s&pwd=%s&mobile=%s&content=%s&ext=&stime=&rrid=&msgfmt=";

	@Override
	public int send(String phone, String content) {
		String url = String.format(SEND_TEMPLATE, host, sn,
				StringUtils.upperCase(CryptUtil.md5(sn + pwd)), phone, content);
		LOG.info("send phone:{},content:{},url:{}", phone, content, url);
		String resp = null;
		try {
			resp = HttpClientHelper.sendRequest(url, "utf-8");
		} catch (Exception e) {
			LOG.info("send retry phone:{}", phone);
			// 重试一次
			try {
				resp = HttpClientHelper.sendRequest(url, "utf-8");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				LOG.error("send error:{}", e1);
			}
		}
		LOG.info("send phone:{} response:{}", phone, resp);
		if (StringUtils.isBlank(resp)) {
			return CODE_FAIL;
		}

		if (StringUtils.startsWith(resp, "-")) {
			return CODE_FAIL;
		} else {
			return CODE_SUCCESS;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.guzhi.service.sms.SmsHandler#isAlive()
	 */
	@Override
	public boolean isAlive() {
		return isAlive;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.guzhi.service.sms.SmsHandler#setAlive(boolean)
	 */
	@Override
	public void setAlive(boolean isAlive) {
		this.isAlive = isAlive;
		if (isAlive) {
			failTimes = 0;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.guzhi.service.sms.SmsHandler#addFails()
	 */
	@Override
	public void addFails() {
		failTimes++;
		if (failTimes >= 3) {
			setAlive(false);
		}
	}

}
